// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var router = require("../hash/pageRouter");
	var css_this = require("./newTaskDetail.css");
	var css_list = require("./newTaskList.css");
	var css_tallyList = require("./tallyListGenerate.css");
	var css_tallyDetail = require("./tallyDetail.css");
	var newTaskDetail = require("./newTaskDetail.js");
	var dialog = require("dialog");
	var validate = require("validate");
	var tools = require("tools");
	var financeId1;
	var databind = require("databind");
	var pageIndex = 1,
		pageSize = 10,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化
	var imgSrc;
	var recieveNoticeId;
	var tallyingId;
	var inventoryHistoryId;
	var type;
	var taskDetail;
	var noticeState;
	var tallyingId;
	var driverAddress = "";
	var left;
	var init = function(page) {
		$(".tallyListGenerate").remove();
		newTaskDetail.init(page);
		recieveNoticeId = page.params.recieveNoticeId || base.getUrlParam("recieveNoticeId");
		tallyingId = page.params.tallyingId || base.getUrlParam("tallyingId");
		inventoryHistoryId = page.params.inventoryHistoryId || base.getUrlParam("inventoryHistoryId");
		driverAddress = page.params.driverAddress;
		tallyingId = page.params.tallyingId;
		type = page.params.type || base.getUrlParam("type");
		
		left = page.params.left || base.getUrlParam("left");
		noticeState = page.params.noticeState || base.getUrlParam("noticeState");
		loadTaskDetail(recieveNoticeId);
		if (inventoryHistoryId != null && inventoryHistoryId.length > 0) {
			inquireTallyingDetail(tallyingId);
		} else {
			showOnselfTally(tallyingId);
		}

		initEvent();
		router.init();

		if (type == "adjust") {
			$("#submitContainerTallying").append("<input type='hidden' value='update' name='type' />");
		}
	};
	var initEvent = function() {
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			top.location.href = "../login/login.html";
		}
		
		$("#tallyDetail").on("click", ".showProductIntroDiv .deleteProductIntro", function() {
			$(this).parent().remove();
			var fileUuid = [];
			for (var j = 0; j < $(".showProductIntroDiv .mas").length; j++) {
				fileUuid.push($($(".showProductIntroDiv .mas")[j]).attr("fileUuid"));
			}
			$("input[name=poundsOfSign]").val(fileUuid);
		});

		//查看理货任务
		$(".page-header").on("click", ".undoneCargoRecord", function() {
			router.route("newTaskList/undoneCargoRecord.html?recieveNoticeId=" + recieveNoticeId, true);
		});

		$(".page-header").on("click", ".taskDetail", function() {
			router.route("newTaskList/newTaskDetail.html?recieveNoticeId=" + recieveNoticeId + "&noticeState=" + noticeState + "&left=" + left, true);
		});

		//点击
		$(".newTaskList").unbind("click").click(function() {
			top.location.href = "../newTaskList/newTaskList.html?noticeState=" + noticeState + "&left=" + left;
		});
		
		$("#tallyDetail").on("change", ".caseNumber", function(){
			var $this = $(this);
			tools.matchs(/^[a-zA-Z]{4}[0-9]{7}$/, $this.val(), "请输入正确的箱号！");
		});

		//上传异常照片
		$("#tallyDetail").on("change", "#uploadFileAbnormalFile1", function() {

			uploadFileImg($(this).parent().parent().attr("id"), $(this).attr("id"));
		});

		//上传异常录音
		$("#tallyDetail").on("change", "#uploadFileSoundRecorde1", function() {

			uploadFile($(this).parent().parent(), "uploadFileSoundRecorde1");
		});

		//上传货物照片
		$(".tallyDetail_main_content").on("change", ".uploadFileInput", function(event) {
//			uploadFileImg($(this).parent().parent().attr("id"), $(this).attr("id"));
			var dom = $(this).parent().parent();
			tools.readFiles(event, $(this).parent().parent(),  $(this).parents("td").find(".bulkstockFilesUuids"),"id11", 'id12', function(data){
				var filesUuids = "";
				$.each($(dom).find("canvas.none"), function() {
					var $this = $(this);
					if ($.trim($this.attr("fileUuid")) != null && $this.attr("fileUuid") != "") {
						if (filesUuids == "") {
							filesUuids = $this.attr("fileUuid");
						} else {
							filesUuids = filesUuids + "," + $this.attr("fileUuid");
						}
					}
				});
				$(dom).parent().find(".bulkstockFilesUuids").val(filesUuids);
			});
		});
		
		
		//上传理货前照片
		$(".tallyDetail_main_content").on("change", "#uploadFilepreTally", function(event) {

//			uploadFileImg($(this).parent().parent().attr("id"), $(this).attr("id"));
			var dom = $(this).parent().parent();
			tools.readFiles(event, $(this).parent().parent(),  $(this).parents("td").find(".preTallyFiles"),"id11", 'id12', function(data){
				var filesUuids = "";
				$.each($(dom).find("canvas.none"), function() {
					var $this = $(this);
					if ($.trim($this.attr("fileUuid")) != null && $this.attr("fileUuid") != "") {
						if (filesUuids == "") {
							filesUuids = $this.attr("fileUuid");
						} else {
							filesUuids = filesUuids + "," + $this.attr("fileUuid");
						}
					}
				});
				$("#tallyDetail .preTallyFiles").val(filesUuids);
			});

		});
		//上传理货后照片
		$(".tallyDetail_main_content").on("change", "#uploadFilesuffixTally", function(event) {

//			uploadFileImg($(this).parent().parent().attr("id"), $(this).attr("id"));
			var dom = $(this).parent().parent();
			tools.readFiles(event, $(this).parent().parent(),  $(this).parents("td").find(".tallySuffixFile"),"id11", 'id12', function(data){
				var filesUuids = "";
				$.each($(dom).find("canvas.none"), function() {
					var $this = $(this);
					if ($.trim($this.attr("fileUuid")) != null && $this.attr("fileUuid") != "") {
						if (filesUuids == "") {
							filesUuids = $this.attr("fileUuid");
						} else {
							filesUuids = filesUuids + "," + $this.attr("fileUuid");
						}
					}
				});
				$("#tallyDetail .suffixTallyFiles").val(filesUuids);
			});

		});

		$(".tallyDetail_main_content").on("click", ".closeLayer", function() {
			var _d = $(this).parent().parent();
			$(this).parent().parent().find(".file").css("display", "inline-block");
			$(this).parent().remove();
			savefilesUuid(_d);
		});

		//提交理货
		$("#submitTally").on("click", function() {
			var ii = layer.load(1, {shade: [0.8, '#393D49']});
			//等待5秒钟
			setTimeout(function(){
				if ($("input[name=recieveNoticeDetailId]").val() == undefined) {
					base.alert(2, "未添加货物，请重新生成一笔理货任务或用手机端理货！");	
					layer.close(ii);
					return;
				};
				
				$.each($(".arrayTally"), function(i, val) {
					if (val.value == undefined || val.value.length == 0) {
						if (val.name == "plannedQuantity" || val.name == "bulkstockId") {
							$(this).val(0);
						} else {
							$(this).val(" ");
						}
					}
				});
				databind.submitDom("#submitContainerTallying", function(d) {
					layer.close(ii);
					base.alert(1, "提交理货成功");
					router.route("newTaskList/undoneCargoRecord.html?recieveNoticeId=" + recieveNoticeId, true);
				});
				
			},4000);
		});
	};
	
	//初始化比例
	var initScale = function() {
		var bulkstock;
		$.each($(".tallyQuantity"), function(i, val) {
			var bulkstockId = $(this).attr("bulkstockId");
			$.each(taskDetail.datas[0].bulkstocks, function(i, val) {
				if (bulkstockId == val.bulkstockId) {
					bulkstock = val;
				}
			});
			var tallyQuantity = $(this).val();
			var max = $(this).attr("max");
			var maxWeight = $(this).attr("maxWeight");
			var maxVolume = $(this).attr("maxVolume");
			var tallyWeight = $(this).parent().parent().find(".tallyWeight").val();
			var tallyVolume = $(this).parent().parent().find(".tallyVolume").val();
			$(this).parent().parent().find(".differenceValueQuantity").html(tallyQuantity - max);
			$(this).parent().parent().find(".differenceValueWeight").html(tallyWeight - maxWeight);
			$(this).parent().parent().find(".differenceValueVolume").html(tallyVolume - maxVolume);
			//				$(this).attr("weightScale", bulkstock.weight / bulkstock.quantity); //重量比例
			//				$(this).attr("volumeScale", bulkstock.volume / bulkstock.quantity); //体积比例
		});

		//绑定理货数量值改变事件
		$(".tallyQuantity").unbind("change").change(function() {
			var tallyQuantity = $(this).val();
			var max = $(this).attr("max");
			var weightScale = $(this).attr("weightScale");
			var volumeScale = $(this).attr("volumeScale");
			//			if(parseFloat(tallyQuantity)>parseFloat(max)){
			//					base.alert(2, "理货数量不能大于计划理货数量"+max);
			//			}
			var maxWeight = $(this).attr("maxWeight");
			var maxVolume = $(this).attr("maxVolume");

			//				$(this).parent().parent().find(".tallyWeight").val((tallyQuantity * weightScale).toFixed(0));
			//				$(this).parent().parent().find(".tallyVolume").val((tallyQuantity * volumeScale).toFixed(0));
			var tallyWeight = $(this).parent().parent().find(".tallyWeight").val();
			var tallyVolume = $(this).parent().parent().find(".tallyVolume").val();
			$(this).parent().parent().find(".differenceValueQuantity").html(tallyQuantity - max);
			$(this).parent().parent().find(".differenceValueWeight").html(tallyWeight - maxWeight);
			$(this).parent().parent().find(".differenceValueVolume").html(tallyVolume - maxVolume);
		});
		
		//绑定理货重量值改变事件
		$(".tallyWeight").unbind("change").change(function() {
			var weightScale = $(this).attr("weightScale");
			var maxWeight = $(this).parents("tr").find(".tallyQuantity").attr("maxWeight");
			var tallyWeight = $(this).parents("tr").find(".tallyWeight").val();
			$(this).parent().parent().find(".differenceValueWeight").html(tallyWeight - maxWeight);
		});
		
		//绑定理货体积值改变事件
		$(".tallyVolume").unbind("change").change(function() {
			var maxVolume = $(this).parents("tr").find(".tallyQuantity").attr("maxVolume");
			var tallyVolume = $(this).parents("tr").find(".tallyVolume").val();
			$(this).parent().parent().find(".differenceValueVolume").html(tallyVolume - maxVolume);
		});
	};
	
	//绑定增加货物相关事件
	var addCommodityEvent = function() {
		$(".caseNumber").unbind("change").change(function() {
			var caseNumber = $(this).val();
			$(this).parent().parent().parent(".page-content-main-content-item").find(".bulkstockCaseNumber").val(caseNumber); //每个货物带集装箱号
		});
		$(".addCommodity").unbind("click").click(function() {
			var number = $(".table").length;
			addCommodityTr($("#commodityContent"), number);
			var caseNumber = $(this).parent().parent(".page-content-main-content-item").find(".caseNumber").val();
			$(this).parent().parent(".page-content-main-content-item").find(".bulkstockCaseNumber").val(caseNumber); //每个货物带集装箱号

			loadTallyBulkstock();
			commodityBulkstockEvent();
		});
	};
	
	//绑定货物相关事件
	var commodityBulkstockEvent = function() {
		//删除所在行
		$(".deleteCommodity").unbind("click").click(function() {
			$(this).parent().parent().parent().parent().remove();
		});

		//绑定点击货物事件
		$(".tallyBulkstockId").unbind("change").change(function() {
			var bulkstock;
			var recieveNoticeDetailId = $(this).val();
			$.each(taskDetail.datas[0].bulkstocks, function(i, val) {
				if (recieveNoticeDetailId == val.recieveNoticeDetailId) {
					bulkstock = val;
				}
			});
			$(this).attr("id", recieveNoticeDetailId);
			databind.fillForm($(this).parent().parent(), bulkstock);
			$(this).parent().parent().find(".plannedQuantity").attr("max", bulkstock.quantity);
			$(this).parent().parent().find(".plannedQuantity").attr("weightScale", bulkstock.weight / bulkstock.quantity); //重量比例
			$(this).parent().parent().find(".plannedQuantity").attr("volumeScale", bulkstock.volume / bulkstock.quantity); //体积比例
			$(this).parent().parent().find(".plannedQuantity").val(bulkstock.quantity);
			$(this).parent().parent().find(".quantityMax").html(bulkstock.quantity);
			$(this).parent().parent().find(".weightMax").html(bulkstock.weight);
			$(this).parent().parent().find(".volumeMax").html(bulkstock.volume);
		});

		//plannedQuantity输入框焦点离开事件
		$(".plannedQuantity").on("blur", function() {
			var max = $(this).attr("max");
			var weightScale = $(this).attr("weightScale");
			var volumeScale = $(this).attr("volumeScale");
			if ($(this).val().search("^-?\\d+$") != 0) {
				base.alert(2, "请输入一个整数");
				return false;
			}
			var plannedQuantity = $(this).val();
			if (parseFloat(plannedQuantity) > parseFloat(max)) {
				base.alert(2, "计划理货不能大于实际收货数量" + max);
			}

			//数量和重量和体积要联动
			$(this).parent().parent().find(".plannedWeight").val((plannedQuantity * weightScale).toFixed(0));
			$(this).parent().parent().find(".plannedVolume").val((plannedQuantity * volumeScale).toFixed(0));
		});
	};
	
	//显示自理界面
	var showOnselfTally = function(tallyingId) {
		var tpl = $("#tallyDetailTpl2").html();
		$(".tallyDetail_main_content").html(tpl);
		tools.loadSelectList($("#tallyDetail select[name=logisticsCompanyInfoId]"), "inquireLogisticsCompanyInfoList.json", "logisticsCompanyInfoId", "logisticsCompanyName", null);
		databind.fillForm($(".tallyDetail_main_content"), {
			tallyingId: tallyingId
		});

		addCommodityEvent();
		loadFinanceWaybillList(taskDetail.datas[0].financeId);
	};

	//加载收货通知
	var loadTaskDetail = function(recieveNoticeId) {
		base.fnAjax({
			action: "inquireRecieveNoticeDetail.json",
			async: false,
			oData: {
				recieveNoticeId: recieveNoticeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					taskDetail = data;
					financeId1 = data.datas[0].financeId;
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};

	//添加货物一行
	var addCommodityTr = function(dom, number) {
		var text = "";
		text += '<table class="table">';
		text += '				<thead>';
		text += '					<tr>';
		text += '						<th>货物名称</th>';
		text += '						<th>规格型号</th>';
		text += '						<th>计划﻿理货数量</th>';
		text += '						<th>重量(吨)</th>';
		text += '						<th>体积(m<sup>3</sup>)</th>';
		text += '						<th>操作</th>';
		text += '					</tr>';
		text += '				</thead>';
		text += '				<tbody class="commodityTable">';
		text += '<tr><td>';
		text += '<input type="hidden" name="bulkstockCaseNumber" class="bulkstockCaseNumber arrayTally" />';
		text += '<select class="tallyBulkstockId field-input weights"  name="bulkstockId">';
		text += '<script type="text/template" class="tallyBulkstockTpl">';
		text += '<option value="">未选</option>';
		text += '{@each bulkstocks as it}';
		text += '<option value="${it.bulkstockId}">${it.bulkstockName}</option>';
		text += '{@/each}';
		text += '</script>';
		text += '</select></td>';
		text += '<td><input type="text" name="specification" class="arrayTally" placeholder="规格型号" readonly="readonly" class="noInput"/></td>';
		text += '<td>';
		text += '<input type="text" placeholder="计划﻿理货数量" class="arrayTally plannedQuantity" name="quantity" minLength="1" maxLength="255" isNull="1" codeName="计划﻿理货数量"/>';
		text += '<br/>理货总数量：<span class="quantityMax"></span>		';
		text += '</td>';
		text += '<td><input type="text" placeholder="重量" class="arrayTally plannedWeight" name="weight" minLength="1" maxLength="255" />';
		text += '<br/>理货总重量：<span class="weightMax"></span>		';
		text += '</td>';
		text += '<td><input type="text" placeholder="体积" class="arrayTally plannedVolume" name="volume" minLength="1" maxLength="255" />';
		text += '<br/>理货总体积：<span class="volumeMax"></span>		';
		text += '</td>';
		//			text += '<td><input type="text" placeholder="计划﻿理货数量" class="arrayTally" name="quantity" minLength="1" maxLength="255" isNull="1" codeName="计划﻿理货数量"/></td>';
		//			text += '<td><input type="text" placeholder="重量" class="arrayTally" name="weight" minLength="1" maxLength="255" isNull="1" codeName="重量"/></td>';
		//			text += '<td><input type="text" placeholder="体积" class="arrayTally" name="volume" minLength="1" maxLength="255" isNull="1" codeName="体积"/></td>';
		text += '<td><a class="deleteCommodity" href="javascript:void(0)">删除</a></td></tr>';
		text += '<tr>';
		text += '	<td colspan="4">货物照片：';
		text += '		<input type="hidden" name="filesUuid" class="bulkstockFilesUuids"  isNull="1" codeName="货物照片"/>';
		text += '		<div class="uploadImgP" id="uploadImgP' + number + '">';
		text += '		<label for="uploadFile' + number + '"  class="file"> 点击上传图片<input type="file" class="uploadFileInput" name="file" id="uploadFile' + number + '" accept=".png,.jpg,.bmp,JPG,PNG,BMP"/></label>';
		text += '		</div>';
		text += '	</td>';
		text += '</tr>';
		text += '	<tr>';
		text += '	<td colspan="4">';
		text += '	<span>货物异常标识：';
		text += '	<select name="bulkstockAbnormal" >';
		text += '	<option value="1">正常</option>';
		text += '	<option value="0">异常</option>';
		text += '	</select>';
		text += '	</span>';
		text += '	<span>货物异常说明：';
		text += '	<textarea name="bulkstockAbnormalComment"></textarea>';
		text += '			</span></td></tr>';
		text += '					</tbody>';
		text += '			</table>';
		dom.before(text);
	};

	//动态加载货物列表数据
	var loadTallyBulkstock = function() {
		var tpl = $(".tallyBulkstockTpl").html();
		var html = juicer(tpl, taskDetail.datas[0]);
		$(".tallyBulkstockId").html(html);
		$.each($(".tallyBulkstockId"), function(i, val) {
			$(this).val(val.id);
		});
	};

	//查询融资箱货明细
	var inquireTallyingDetail = function(inventoryId) {
		base.fnAjax({
			action: "inquireTallyingDetail.json",
			oData: {
				tallyingId: tallyingId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					juicer.register("inquireFile", tools.inquireFile);
					var tpl = $("#tallyDetailTpl").html();
					var html = juicer(tpl, data);
					$(".tallyDetail_main_content").html(html);
					tools.loadSelectList($("#tallyDetail select[name=logisticsCompanyInfoId]"), "inquireLogisticsCompanyInfoList.json", "logisticsCompanyInfoId", "logisticsCompanyName", null);
					
					data.datas[0].logisticsCompanyInfoId = data.datas[0].containerInventorys[0].logisticsCompanyInfoId;
					databind.fillForm($("#submitContainerTallying"), data.datas[0]);
					$.each($(".bulkstockFilesUuids"), function(i, val) {
						showImg($(this).parent().find(".uploadImgP"), val.value);
					});
					$.each($(".suffixTallyFiles"), function(i, val) {
						showImg($(this).parent(), val.value);
					});
					$.each($(".preTallyFiles"), function(i, val) {
						showImg($(this).parent(), val.value);
					});
					//异常录音
					$.each($("#soundRecorde1"), function(i, val) {
						showImg($(this).parent(), val.value);
					});
					//异常图片
					$.each($("#abnormalFile1"), function(i, val) {
						showImg($(this).parent(), val.value);
					});

					loadFinanceWaybillList(data.datas[0].financeId);
					//点击理货异常
					$(".tallyAbnormal").on("change", function() {
						if ($(this).val() == 0) {
							$(".abnormalDiv").removeClass("none");
						} else {
							$(".abnormalDiv").addClass("none");
						}
					});
					initScale();
					databind.fillInput1($(".page-content-main-content-item11"), {action:"inquireTallyingDetail.json?tallyingId="+tallyingId, version:"v1.0"}, function(){
						$("#tallyDetail #tallyingFile").val(tools.inquireFile($("#tallyDetail #tallyingFile").val()));
					});
					
					if (financeId1 == 0) {
						$("#tallyDetail .waybillNumber").replaceWith('<input class="waybillNumber" type="text" name="waybillNumber" />');
					}
					
					var waybillNumber_ = $(".waybillNumber").attr("id");
					
					if($(".waybillNumber").attr("readonly")=="readonly"){
						$(".waybillNumber").html("<option value="+waybillNumber_+">"+waybillNumber_+"</option>");
					}
					
					if (data.datas[0].abnormal == 0) { //如果理货异常出现异常单
						$(".abnormalDiv1").removeClass("none");
						$(".abnormalDiv1 select[name=tallyExAbnormalState]").val($(".abnormalDiv1 select[name=tallyExAbnormalState]").attr("value"));
					}
					
					tools.fileupload($("#poundsOfSign"), null, function(data){
						var str = '<div class="showProductIntroDiv"><a target="_blank" class="mas" fileUuid="' + data.result.data[0].fileUuid + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + data.result.data[0].fileUuid + '" class="showProductIntro">' + data.result.data[0].fileName + '</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="deleteProductIntro">x</a></div>'
						$("#tallyDetail .fs").append(str);
						
						var fileUuid = [];
						for (var j = 0; j < $("#tallyDetail .showProductIntroDiv .mas").length; j++) {
							fileUuid.push($($("#tallyDetail .showProductIntroDiv .mas")[j]).attr("fileUuid"));
						}
						$("#tallyDetail input[name=poundsOfSign]").val(fileUuid);
					});
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};

	var loadFinanceWaybillList = function(financeId) {
		base.fnAjax({
			action: "inquireFinanceWaybillList.json",
			async: false,
			oData: {
				financeId: financeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var tpl = $("#financeWaybillListTpl").html();
					var html = juicer(tpl, data);
					$(".waybillNumber").html(html);

					if ("readOnly" == type) {
						databind.disableInput($("#submitContainerTallying"));
						$(".acceptTasks").css("display", "none");
						$(".uploadImgP").find(".file").css("display", "none");
						$(".closeLayer").css("display", "none");
						$(".uploadFilepreTallyP").css("display", "none");
						$(".uploadFilesuffixTallyP").css("display", "none");
						$("#submitTally").css("display", "none");
						$("#submitTally").parent().css("display", "none");
//							html = '<div id="updateTally" class="updateTally dialogBtn dialogHandlerBtn">修改理货</div>';
						$("#submitTally").parent().append(html);

						$("#updateTally").unbind("click").click(function() {
							$(".uploadImgP").find(".file").css("display", "block");
							$(".closeLayer").css("display", "block");
							$(".uploadFilepreTallyP").css("display", "block");
							$(".uploadFilesuffixTallyP").css("display", "block");
							$("#submitTally").css("display", "block");
							$("#submitTally").css("display", "block");
							databind.enableInput($("#submitContainerTallying"));
							$("#updateTally").css("display", "none");
						});

						$("#soundRecordeP").addClass("none");
						$("#abnormalFileP").addClass("none");
					}

				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};
	
	//显示图片
	var showImg = function(dom, fileUuid) {
		var fileUuids = fileUuid.split(",");
		var html = "";
		var imgSrc = "";
		for (var i = 0; i < fileUuids.length; i++) {
			imgSrc = fileUuids[i];
			if (imgSrc.length != 0) {
				html = "<label style='width:100px; height:50px' class=\"finance-file\">" + "<a style='display:block; width:85px; height:85px; position:absolute;' target='_blank' href='/finance/api/1.0/downloadFile.file?fileUuid=" + imgSrc +"'></a>" +
								"<img alt='"+imgSrc+"' src=\"/finance/api/1.0/downloadFile.file?fileUuid=" + imgSrc + "\" class=\"finance-field-img\"/>" + " <a class=\"closeLayer\" ></a></label>";
				$(dom).append(html);
			}
		}
	};

	var uploadFile = function(dom, id) { //p标签的dom,img的id
		if ($("#" + id).val() != "") {
			$.ajaxFileUpload({
				url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
				secureuri: false,
				fileElementId: id,
				dataType: 'json',
				success: function(data) {
					var imgSrc = "";
					var html = "";
					imgSrc = data.data[0].fileUuid;
					html = "<label class=\"finance-file\"><img  src=\"../../../res/png/voice_icon.png\" class=\"finance-field-img\"  alt=\"" + imgSrc + "\"  /> <a id=\"closeLayer1\" class=\"closeLayer\" ></a></label>";
					dom.append(html); //
					$("#soundRecorde1").val(imgSrc);
					$(".uploadFileSoundRecorde1").css("display", "none");
				},
				complete: function(xml) {},
				error: function(data, status, e) {
					if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
				}
			});
		} else {
			base.alert(3, "请选择文件！");
		}
	};

	var uploadFileImg = function(domId, id) { //指定p标签的dom的ID,img的id
		if ($("#" + id).val() != "") {
			var fileType = "jpg,png,bmp,JPG,PNG,BMP";
			var prompt = validate.validateFileType($("#" + domId).find("#" + id), fileType);
			if (prompt.length > 1) {
				base.alert(2, prompt);
				return;
			}
			$.ajaxFileUpload({
				url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
				secureuri: false,
				fileElementId: id,
				dataType: 'json',
				success: function(data) {
					imgSrc = data.data[0].fileUuid;
//					var html = "<label class=\"finance-file\"><img  src=\"/finance/api/1.0/downloadFile.file?fileUuid=" + imgSrc + "\" class=\"finance-field-img\"  alt=\"" + imgSrc + "\"  /> <a class=\"closeLayer\" ></a></label>";
//	
//					$("#" + domId).append(html);
					if ($("#" + domId).find(".finance-field-img").length == 8) {
						$("#" + domId).find(".file").css("display", "none");
					}
					
					if (window.chrome != null) {
						var html = "<label class=\"finance-file\"><img  src=\"/finance/api/1.0/downloadFile.file?fileUuid=" + imgSrc + "\" class=\"finance-field-img\"  alt=\"" + imgSrc + "\"  /> <a class=\"closeLayer\" ></a></label>";
						$("#" + domId).append(html)
						savefilesUuid($("#" + domId));
					} else {
						var _this = document.getElementById(id);
						var files = !!_this.files ? _this.files : [];
						if (!files.length || !window.FileReader) return;
						if (/^image/.test(files[0].type)){
					        // Create a new instance of the FileReader
					        var reader = new FileReader();
					        // Read the local file as a DataURL
					        reader.readAsDataURL(files[0]);
					        // When loaded, set image data as background of div
					        reader.onloadend = function(){
					        	var src = "<label class='finance-file'><img  src='" + this.result + "' class='finance-field-img'  alt='" + imgSrc + "'  /> <a class='closeLayer' ></a></label>";
								$("#" + domId).append(src);
								savefilesUuid($("#" + domId));
					        }
					    }
					}
					
				},
				complete: function(xml) {},
				error: function(data, status, e) {
					if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
				}
			});
		} else {
			base.alert(3, "请选择文件！");
		}
	};

	//更新fileUuuid保存字段
	var savefilesUuid = function(dom) {
		var filesUuids = "";
		var imgDom = dom.find(".finance-field-img");
		var number = imgDom.length;
		$.each(imgDom, function(i, object) {
			var $this = $(this);
			if (filesUuids == "") {
				filesUuids = $(this).attr("alt");
			} else {
				filesUuids = filesUuids + "," + $(this).attr("alt");
			}
		});
		dom.parent().find(".bulkstockFilesUuids").val(filesUuids);
		dom.parent().find(".suffixTallyFiles").val(filesUuids);
		dom.parent().find(".preTallyFiles").val(filesUuids);
		dom.parent().find("#soundRecorde1").val(filesUuids);
		dom.parent().find("#abnormalFile1").val(filesUuids);
	};
	
	return {
		init: init
	};
});